package com.example.imtao.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.imtao.LessonResult;
import com.example.imtao.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class FindFragment extends Fragment {


    private String mResult;
    private TextView neirong;
    private TextView laiyuan;
    private ImageView picc;
    private TextView neirong2;
    private TextView laiyuan2;
    private ImageView picc2;
    private TextView neirong3;
    private TextView laiyuan3;
    private ImageView picc3;
    private String url;
    private String url2;
    private String url3;
    private LinearLayout new1;
    private LinearLayout new2;
    private LinearLayout new3;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_find,container,false);
        neirong=view.findViewById(R.id.neirong);
        laiyuan=view.findViewById(R.id.laiyuan);
        picc=view.findViewById(R.id.pic);
        neirong2=view.findViewById(R.id.neirong2);
        laiyuan2=view.findViewById(R.id.laiyuan2);
        picc2=view.findViewById(R.id.pic2);
        neirong3=view.findViewById(R.id.neirong3);
        laiyuan3=view.findViewById(R.id.laiyuan3);
        picc3=view.findViewById(R.id.pic3);
        new1=view.findViewById(R.id.new1);
        new2=view.findViewById(R.id.new2);
        new3=view.findViewById(R.id.new3);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());

        new Thread(new Runnable() {
            @Override
            public void run() {

                requestDataByGet();


            }
        }).start();


        new1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri=Uri.parse(url);
                Intent intent=new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }
        });
        new2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri=Uri.parse(url2);
                Intent intent=new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }
        });
        new3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri=Uri.parse(url3);
                Intent intent=new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }
        });

        return  view;


    }

    private void handleJSONData(String result) {
        Log.d("TAGTAG", "handleJSONData start");
        LessonResult lessonResult=new LessonResult();
        try {
            Log.d("TAGTAG", "开始解析");
            JSONObject jsonObject1 = new JSONObject(result);
            Log.d("TAGTAG", "1");
            String result1=jsonObject1.getString("result");

            JSONObject jsonObject = new JSONObject(result1);

            int status = jsonObject.getInt("stat");
            JSONArray lessons = jsonObject.getJSONArray("data");
            Log.d("TAGTAG", "lessons.size ="+lessons.length());
            if(lessons ==null ){
                Log.d("TAGTAG", "lessons==null");
            }
            lessonResult.setmStatus(status);
            if(lessons !=null && lessons.length()>0){
                Log.d("TAGTAG", "lessons="+lessons);
                JSONObject lesson=(JSONObject)lessons.get(0);
                if(lesson==null){
                    Log.d("TAGTAG", "lesson==null");
                }else {
                    Log.d("TAGTAG", "lesson="+lesson);
                }


                String title=lesson.getString("title");
                if(title==null){
                    Log.d("TAGTAG", "title == null");
                }else{
                    Log.d("TAGTAG", "title="+title);
                }

                String name=lesson.getString("author_name");
                if(name==null){
                    Log.d("TAGTAG", "name == null");
                }
                url=lesson.getString("url");
                String pic=lesson.getString("thumbnail_pic_s");
                neirong.setText(title);
                laiyuan.setText(name);

                picc.setImageBitmap(returnBitMap(pic));

                JSONObject lesson2=(JSONObject)lessons.get(1);
                String title2=lesson2.getString("title");
                String name2=lesson2.getString("author_name");
                url2=lesson2.getString("url");
                String pic2=lesson2.getString("thumbnail_pic_s");
                neirong2.setText(title2);
                laiyuan2.setText(name2);
                picc2.setImageBitmap(returnBitMap(pic2));

                JSONObject lesson3=(JSONObject)lessons.get(2);
                String title3=lesson3.getString("title");
                String name3=lesson3.getString("author_name");
                url3=lesson3.getString("url");
                String pic3=lesson3.getString("thumbnail_pic_s");
                neirong3.setText(title3);
                laiyuan3.setText(name3);
                picc3.setImageBitmap(returnBitMap(pic3));


            }

        } catch (JSONException e) {
            Log.d("TAGTAG", "error");
            e.printStackTrace();
        }




    }


    public String streamToString(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new  byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            baos.close();
            is.close();
            byte[] byteArray=baos.toByteArray();
            return new String(byteArray);
        }catch (Exception e){

            return null;
        }


    }

    public static String decode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    private void requestDataByGet(){

        try {
            URL url=new URL("http://v.juhe.cn/toutiao/index?type=&page=&page_size=&key=9f35169291647c22f759869883915b46");
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Charset","UTF-8");
            connection.setRequestProperty("Accept-Charset","UTF-8");
            connection.connect();

            int responseCode = connection.getResponseCode();
            String responseMessage = connection.getResponseMessage();

            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                mResult = streamToString(inputStream);

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        handleJSONData(mResult);

                    }
                });




            }



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }




    public Bitmap returnBitMap(String url){

        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        }
        catch (MalformedURLException e){e.printStackTrace();
        }
        try {
            HttpURLConnection conn =(HttpURLConnection)myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {e.printStackTrace();}
        return bitmap;}



}
